package serializable;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.*;
@SpringBootTest
@RunWith(SpringRunner.class)
public class SerializeOperation {
    /**
     * 序列化对象，并使用了try-with-resources
     * @param student
     * @param path
     * @throws IOException
     */
    static final String path = "D:/student.txt";

    public static void main(String[] args) throws IOException {
//        serializeToFile(new Student("小明",16,"翻斗花园"),path);
        deserializationFromFile(path);
    }
    @Test
    public static void serializeToFile(Student student, String path) throws IOException {
        Student s = new Student("小明",16,"翻斗花园");
        try(FileOutputStream fileOut = new FileOutputStream(path);
            ObjectOutputStream out = new ObjectOutputStream(fileOut);) {
            out.writeObject(s);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    /**
     * 反序列化对象
     * @param path
     */
    @Test
    public static void deserializationFromFile(String path){
        try(FileInputStream fileIn = new FileInputStream(path);
            ObjectInputStream in = new ObjectInputStream(fileIn);){
            Student s = (Student) in.readObject();
            System.out.println(s.getAddress());
            System.out.println(s.getAge());
            System.out.println(s.getName());
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}